package com.msconfig.mvp.view.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.device.DeviceManage;
import com.msconfig.event.DebugCommandDialogDismissEvent;
import com.msconfig.event.SaveDataToFileSuccessEvent;
import com.msconfig.io.ReceiverListener;
import com.msconfig.mvp.view.activity.SetupDebugCommandDialogActivity;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;
import com.msconfig.mvp.view.adapter.DebugCommandRecycleviewAdapter;
import com.msconfig.utils.GeneralUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.msconfig.bluetooth.BlueToothInit.PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE;


public class SetupDebugFragment extends BaseMvpFragment implements View.OnClickListener {
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private RelativeLayout rlSendCommand;
    private EditText etSendCommand;
    private RelativeLayout rlCommands;
    private LinearLayout rlDebugChoose;
    private RecyclerView recyclerView;
    private DebugCommandRecycleviewAdapter adapter;
    private Button btnStop;
    private Button btnStart;
    private Button btnSend;
    private Button btnClear;
    private CheckBox cbSave;
    private CheckBox cbShowDebugCommand;
    private TextView tvCommand;
    private ArrayList<String> list;
    private ArrayList<String> receiveLists;
    private boolean isGnssCommand=false;
    private boolean isSavaOk=false;
    private boolean isClickBtnSend=false;
    private String command = "";
    private Context context;
    private boolean isStopReceiveData;
    private SimpleDateFormat simpleDateFormat;
    private String date;
    private String debugMessage;
    private StringBuilder debugMessageBuilder;
    private ReceiverListener receiverListener;
    private MyHandler myHandler;


    public static SetupDebugFragment newInstance() {
        Bundle args = new Bundle();
        final SetupDebugFragment fragment = new SetupDebugFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_setup_debug;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);
        rlSendCommand = (RelativeLayout)view.findViewById( R.id.rl_send_command );
        etSendCommand = (EditText)view.findViewById( R.id.et_send_command );
        rlCommands = (RelativeLayout)view.findViewById( R.id.rl_commands );
        rlDebugChoose = (LinearLayout)view.findViewById( R.id.rl_debug_choose );
        recyclerView = (RecyclerView)view.findViewById( R.id.recycler_view );
        btnStop = (Button)view.findViewById( R.id.btn_stop );
        btnStart = (Button)view.findViewById( R.id.btn_start );
        btnSend = (Button)view.findViewById( R.id.btn_send );
        btnClear = (Button)view.findViewById( R.id.btn_clear );
        tvCommand = (TextView) view.findViewById( R.id.tv_command );
        cbSave = (CheckBox) view.findViewById( R.id.cb_save );
        cbShowDebugCommand = (CheckBox) view.findViewById( R.id.cb_show_debug_command );
    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
        btnStop.setOnClickListener( this );
        btnStart.setOnClickListener( this );
        btnSend.setOnClickListener( this );
        btnClear.setOnClickListener( this );
        rlCommands.setOnClickListener( this );
        cbSave.setOnClickListener( this );
        cbShowDebugCommand.setOnClickListener( this );
    }

    //负责更新UI
    private static class MyHandler extends Handler {
        WeakReference<SetupDebugFragment> weakReference;

        private MyHandler(SetupDebugFragment fragment) {
            weakReference = new WeakReference<SetupDebugFragment>(fragment);
        }
        @Override
        public void handleMessage(Message msg) {
            SetupDebugFragment fragment = weakReference.get();
            if (fragment != null) {
                String receiveData= (String) msg.obj;
                String receiveDatas[]=receiveData.split("\r\n");
                if(receiveDatas.length>0){
                    for(int j=0;j<receiveDatas.length;j++){
                        fragment.receiveLists.add(receiveDatas[j]);
                        fragment.showDataOnListView(receiveDatas[j]);
                    }
                }
            }
        }
    }

    @Override
    protected void initData() {
        tvCommonTitle.setText(R.string.title_debug);
        list=new ArrayList<>();
        myHandler=new MyHandler(this);
        receiveLists=new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new DebugCommandRecycleviewAdapter(list);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(context.getDrawable(R.drawable.shape_view));
        recyclerView.addItemDecoration(dividerItemDecoration);
        recyclerView.setAdapter(adapter);

        receiverListener=new ReceiverListener() {
            @Override
            public void OnReceiverCallBack(int nLength, byte[] data) {
                Log.d("Debug-OnReceiverCall", new String(data,0,nLength));
                //显示接收到的所有数据
                String receiveData=new String(data,0,nLength);
                Message msg=new Message();
                msg.obj=receiveData;
                myHandler.sendMessage(msg);

            }
        };
        DeviceManage.getInstance().RegReceiverListener(receiverListener);
    }

    @Override
    public void onDestroyView() {
        //DeviceManage.getInstance().UnReceiverListener();
        super.onDestroyView();
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Override
    public void onClick(View v) {
        if(v==ivCommonBack){
            backTo();
        }else if(v==rlCommands){
            Intent intent=new Intent(getActivity(), SetupDebugCommandDialogActivity.class);
            startActivity(intent);
        }else if(v==btnStop){
            onClickBtnStop();
        }else if(v==btnStart){
            onClickBtnStart();
        }else if(v==btnClear){
            list.clear();
            adapter.notifyDataSetChanged();
        }else if(v==btnSend){
            isClickBtnSend=true;
            String command=etSendCommand.getText().toString().trim();
            if(command.equals("")){
                Toast.makeText(getContext(),"发送内容不能为空！", Toast.LENGTH_SHORT).show();
                return;
            }
            if(!DeviceManage.getInstance().isConnected()){
                Toast.makeText(getContext(),R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                return;
            }
            String strCommand=command+"\r\n";
            DeviceManage.getInstance().sendCommand(strCommand);
        }else if(v==cbSave){
            debugMessageBuilder = new StringBuilder();
            simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmm");
            date=simpleDateFormat.format(System.currentTimeMillis());
            requestPermission();
            if(cbSave.isChecked() && isSavaOk){
                if(receiveLists.size()!=0){
                    for(String message:receiveLists){
                        debugMessage = debugMessageBuilder.append(message+"\r\n").toString();
                    }
                    GeneralUtil.writeMessageToFile(debugMessage,"/Debug_"+date+".txt");
                }
            }
        }else if(v==cbShowDebugCommand){
            if(cbShowDebugCommand.isChecked()){
                isGnssCommand=true;
            }else{
                isGnssCommand=false;
            }
        }
    }

    //保存文件开启存储权限
    public void requestPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getContext().checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
        }else {
            isSavaOk=true;
        }
    }

    //权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            isSavaOk=true;
            if(cbSave.isChecked() && isSavaOk){
                if(receiveLists.size()!=0){
                    for(String message:receiveLists){
                        debugMessage = debugMessageBuilder.append(message+"\r\n").toString();
                    }
                    GeneralUtil.writeMessageToFile(debugMessage,"/Debug_"+date+".txt");
                }
            }
        }
    }


    private void onClickBtnStart() {
        isStopReceiveData=false;
        btnStart.setVisibility(View.GONE);
        btnStop.setVisibility(View.VISIBLE);
    }

    private void onClickBtnStop() {
        isStopReceiveData=true;
        btnStart.setVisibility(View.VISIBLE);
        btnStop.setVisibility(View.GONE);
    }

    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showDebugCommand(DebugCommandDialogDismissEvent event) {
        String commmandName=event.getCommand();
        tvCommand.setText(commmandName);
        if(commmandName.equals(getString(R.string.instrument_self_inspection))){
            command=getString(R.string.command_device_self_check);
        }else if(commmandName.equals(getString(R.string.reset_motherboard))){
            command=getString(R.string.command_gps_reset);
        }else if(commmandName.equals(getString(R.string.stop_message_output))){
            command=getString(R.string.command_unlogall);
        }else if(commmandName.equals(getString(R.string.message_output))){
            command=getString(R.string.command_logall);
        }else if(commmandName.equals(getString(R.string.host_restart))){
            command=getString(R.string.command_device_reset);
        }else if(commmandName.equals(getString(R.string.restore_factory_settings))){
            command=getString(R.string.command_device_freset);
        }else if(commmandName.equals(getString(R.string.read_motherboard_serial))){
            command=getString(R.string.command_gps_info_serial);
        }else if(commmandName.equals(getString(R.string.read_motherboard_firmware_ver))){
            command=getString(R.string.command_gps_info_firmware_ver);
        }else if(commmandName.equals(getString(R.string.apply_for_gga_output))){
            command=getString(R.string.command_gga_ontime_1s);
        }else if(commmandName.equals(getString(R.string.gps_rtktimeout))){
            command=getString(R.string.command_gps_rtktimeout_3000);
        }else if(commmandName.equals(getString(R.string.close_gps_rtktimeout))){
            command=getString(R.string.command_gps_rtktimeout_30);
        }else if(commmandName.equals(getString(R.string.direct_to_mainboard))){
            command=getString(R.string.command_gps_command);
        }
        etSendCommand.setText(command);
    }



    private void showDataOnListView(String receiveData) {
        if(isStopReceiveData)
            return;
        if(isGnssCommand){
            //显示调试的命令
            if(receiveData.startsWith("@GNSS")){
                list.add(receiveData);
                adapter.notifyDataSetChanged();
            }
            return;
        }
        list.add(receiveData);
        adapter.notifyDataSetChanged();
        recyclerView.smoothScrollToPosition(adapter.getItemCount()-1);
    }

    //保存文件成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void saveDataToFileSuccess(SaveDataToFileSuccessEvent event) {
        Toast.makeText(getContext(),getString(R.string.toast_save_file)+event.getPath(), Toast.LENGTH_SHORT).show();
    }
}
